package com.wakala.employment.fragment.other;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.broccoli.BroccoliSimpleDelegateAdapter;
import com.wakala.employment.adapter.base.delegate.SimpleDelegateAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentCommunicateMeRecordBinding;
import com.wakala.employment.fragment.news.NewDetailFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.ArticlePage;
import com.wakala.employment.http.bean.ArticleVo;
import com.wakala.employment.http.bean.UserCommunicateRecordPage;
import com.wakala.employment.http.bean.UserCommunicateRecordRequest;
import com.wakala.employment.http.bean.UserCommunicateRecordVo;
import com.wakala.employment.utils.DemoDataProvider;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.tip.ToastUtils;

import me.samlss.broccoli.Broccoli;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CommunicateMeRecordFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class CommunicateMeRecordFragment extends BaseFragment<FragmentCommunicateMeRecordBinding> implements View.OnClickListener {

    private static String TAG = "CommunicateMeRecordFragment";

    private SimpleDelegateAdapter<UserCommunicateRecordVo> mNewsAdapter;
    int page = 1;
    int pageSize = 10;
    /**
     * 查询条件
     */
    private UserCommunicateRecordRequest request;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public CommunicateMeRecordFragment() {
        // Required empty public constructor
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        request = new UserCommunicateRecordRequest();
    }

    @NonNull
    @Override
    protected FragmentCommunicateMeRecordBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentCommunicateMeRecordBinding.inflate(inflater, container, attachToRoot);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected TitleBar initTitle() {
        return null;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CommunicateMeRecordFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CommunicateMeRecordFragment newInstance(String param1, String param2) {
        CommunicateMeRecordFragment fragment = new CommunicateMeRecordFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initViews() {
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(getContext());
        binding.recyclerView.setLayoutManager(virtualLayoutManager);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        binding.recyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 10);

        mNewsAdapter = new BroccoliSimpleDelegateAdapter<UserCommunicateRecordVo>(R.layout.adapter_communicate_view_list_item, new LinearLayoutHelper(), DemoDataProvider.getEmptyCommunicateRecord()) {
            @Override
            protected void onBindData(RecyclerViewHolder holder, UserCommunicateRecordVo model, int position) {
                if (model != null) {
                    holder.text(R.id.tv_user_name, model.getUserName());
                    holder.text(R.id.tv_tag, model.getTag());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_summary, Html.fromHtml(model.getSummary(),Html.FROM_HTML_MODE_COMPACT));
                    holder.click(R.id.tv_summary, v -> {
                       //TODO 跳转详情页
                    });
                }
            }

            @Override
            protected void onBindBroccoli(RecyclerViewHolder holder, Broccoli broccoli) {
                broccoli.addPlaceholders(
                        holder.findView(R.id.tv_user_name),
                        holder.findView(R.id.tv_tag),
                        holder.findView(R.id.tv_title),
                        holder.findView(R.id.tv_summary)
                );
            }
        };

        DelegateAdapter delegateAdapter = new DelegateAdapter(virtualLayoutManager);
        delegateAdapter.addAdapter(mNewsAdapter);

        binding.recyclerView.setAdapter(delegateAdapter);
    }

    @Override
    protected void initListeners() {
        //下拉刷新
        binding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            request.setPage(1);
            getArticleList("fresh");
        });
        //上拉加载
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            int currentPage = mNewsAdapter.getItemCount() / pageSize + 1;
            request.setPage(currentPage);
            getArticleList("more");
        });
        //设置刷新加载时禁止所有列表操作
        binding.refreshLayout.setDisableContentWhenRefresh(true);
        binding.refreshLayout.setDisableContentWhenLoading(true);
        binding.refreshLayout.autoRefresh();//第一次进入触发自动刷新
    }

    @Override
    public void onClick(View view) {

    }

    @SuppressLint("CheckResult")
     private void getArticleList(String type) {
        XHttpProxy.proxy(TestApi.IUserService.class)
                .userCommunicateRecordList(request)
                .subscribeWith(new NoTipRequestSubscriber<UserCommunicateRecordPage>() {
                    @SuppressLint("CheckResult")
                    @Override
                    protected void onSuccess(UserCommunicateRecordPage commonPageApiResult) {
                        Log.i(TAG, "-------------沟通信息列表------------------");
                        Log.i(TAG, GsonUtils.toJson(commonPageApiResult));
                        if (type.equals("fresh")) {
                            mNewsAdapter.refresh(commonPageApiResult.getList());
                            binding.refreshLayout.finishRefresh();
                            if(commonPageApiResult.getList().isEmpty()){
                                ToastUtils.toast("没有符合条件的数据");
                                binding.llStateful.showEmpty("没有符合条件的数据");
                            }else{
                                 binding.llStateful.showContent();
                            }
                        }else if(type.equals("more")){
                            if(commonPageApiResult.getList().isEmpty()){
                                //展示无数据孔状态
                                binding.refreshLayout.finishLoadMoreWithNoMoreData();
                                ToastUtils.toast("已更新到最新数据");
                            }else {
                                mNewsAdapter.loadMore(commonPageApiResult.getList());
                                binding.refreshLayout.finishLoadMore();
                            }

                        }

                        Log.i(TAG, "-------------沟通信息列表------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        // binding.refreshLayout.finishLoadMore();
                        ToastUtils.toast(e.getDisplayMessage());
                        if (type.equals("fresh")){
                            binding.refreshLayout.finishRefresh();
                        } else if (type.equals("more")) {
                            binding.refreshLayout.finishLoadMore();
                        }
                        binding.llStateful.showError("加载数据失败", "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                getArticleList("fresh");
                            }
                        });
                        Log.i(TAG, "-------------沟通信息列表-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });

    }


}